<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :rules="rules" :inline="true" @submit.native.prevent>

      <div   style="height: 40px">

        <el-form-item label="选择日期"  prop="rawDate">
          <el-date-picker
            v-model="rawDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>

          </el-form-item>
<!--      </div>-->
<!--      <div v-if="searchGroup" >-->
<!--       -->

        <el-form-item label="班次" prop="classesName">
          <el-select v-model="queryParams.classesName" placeholder="请选择" clearable size="small"
                     style="position: relative;top: 2px;width: 100px" @change="handleQuery">
            <el-option
              v-for="classes in classesList"
              :key="classes.classesId"
              :label="classes.classesName"
              :value="classes.classesName"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="班组" prop="teamName" v-if="searchGroup">-->
<!--          <el-select v-model="queryParams.teamName" placeholder="请选择" clearable size="small"-->
<!--                     style="position: relative;top: 2px;width: 100px" @change="handleQuery">-->
<!--            <el-option-->
<!--              v-for="team in teamList"-->
<!--              :key="team.teamId"-->
<!--              :label="team.teamName"-->
<!--              :value="team.teamName"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="钢种" prop="steelGrade">-->
<!--          <el-input v-model="queryParams.steelGrade" placeholder="请输入钢种"/>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh-right" size="mini" @click="rebuild">重置</el-button>

        </el-form-item>
      </div>

    </el-form>

    <el-row>
      <el-col :span="12">
        <div ref="chart1"  :style="{height:windowHeight*0.4+'px',width:'100%'}"></div>
      </el-col>
      <el-col :span="12">
        <div ref="chart2"  :style="{height:windowHeight*0.4+'px',width:'100%'}"></div>
      </el-col>
    </el-row>
    <el-row>
      <div ref="chart3" :style="{height:windowHeight*0.45+'px',width:'100%'}"></div>
    </el-row>


  </div>
</template>

<script>
// import {exportSmeltingGroup, listGroup, pageGroup} from '@/api/app/smelt/group'
import{listAnalysis, pageAnalysis} from '@/api/app/productionMat/analysis'
import {listClasses} from '@/api/app/group/classes'
import {listTeam} from '@/api/app/group/team'
import moment from "moment/moment";
import yearPicker  from "./YearRangePicker.vue";
import * as echarts from "echarts";
import {listConsumption,getMatrialName,getHisMatrialByDate} from "@/api/app/productionMat/consumption";
import {getLastSche} from "@/api/app/group/sche";


export default {
  components: {
    yearPicker
  },
  data() {
    return {
      windowWidth: document.documentElement.clientWidth, // 实时屏幕宽度
      windowHeight: document.documentElement.clientHeight,// 实时屏幕高度
      total: 0,
      tableHeight:this.tableHeight,
      // 查询参数
      queryParams: {

        classesName: null,
        // groupName: null,
        // year: this.moment().format('YYYY'),
        // month: this.moment().format('M'),
        // day: null,//this.moment().format('YYYY-MM-DD'),
        rawDate:null,
        // tableType:1,//报表类型，默认日报表
        dateType: 0,
        // steelGrade:null,
        // lfNo: 1
      },
      dateRangeTeam: [this.moment().format('YYYY-MM-01'), this.moment().format('YYYY-MM-DD')],
      dateRangeTime: [,],
      yearRange:['',''],
      searchGroup: false,
      //searchType: 1,
      classesList: [],
      teamList: [],
      // 表格数据
      list: [],
      rules: {
        rawDate: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ]
      },
      rawDate:moment(new Date()).format('YYYY-MM-DD'),
      chart1Instance:null,
      chart2Instance:null,
      chart3Instance:null,
      consumptionList:[],
      pie1Data:[],
      pie1Legend:[],
      barData:[],
      barName:[],
      costConsumptionList:[],
      materialNameMap:new Map(),
      dt:[],//时间

      materialHisList:null,//包含dt
      valueHisList:new Map(),//不包含数据 key：物料名；value:dataList
      chart:{
        name:"",

        values:[],
      },
      chartList:[],
      queryHisParams:{
        tableTag:"st2",
        timeTag:2,
        beginDate:null,
        endDate:null,
        rawDate:null,
      }

    }
  },

  computed: {
    yearOptions() {
      let res = []
      for (let i = 2022; i <= this.moment().format('YYYY'); i++) {
        res.push(i)
      }
      return res
    }
  },
async  created() {
    // await getConfigKey('prodCode').then(res => {
    //   this.queryParams.prodCode = res.msg
    // })
  this.getClassesList()
  this.getTeamList()

  },
  mounted() {
    this.initCanvas();
    this.getLastSche()//已经调用了getData


    // this.getData();


    this.tableHeight = (window.innerHeight - 270)  + "px"; //260即表格之外的固定高度

    window.onresize = () => {
      return (() => {
        this.tableHeight = (window.innerHeight -270)  + "px";

      })();
    };
  },
  methods: {
    //表头样式，
     renderHeader(h, { column, $index }) {
      let columnArr = column.label.split("||");//此处换行标志
      if (columnArr.length >= 2) {
        let divArr = [];
        columnArr.map((item) => {
          divArr.push(h("div", { style: "text-align: center " }, item));
        });
        return h("div", {}, divArr);
      }
      return h("div", {}, column.label);
    },

getClassesList() {
      listClasses({}).then(res => {
        this.classesList = res.data.rows
      })
    },
    getTeamList() {
      listTeam({}).then(res => {
        this.teamList = res.data.rows
      })
    },
    getLastSche(){
      getLastSche({}).then(res => {
        if(res.data !== null)
        {
          for(let i = 0;i<this.classesList.length;i++){
            if(this.classesList.at(i).classesId === res.data.classesId){
              this.queryParams.classesName = this.classesList.at(i).classesName
              this.rawDate = res.data.scheDate
              break;
            }
          }

        }
        this.getData()
      })
    },
    /** 查询班次列表 */
    getList() {
      this.loading = true
      this.queryParams.beginDate = null
      this.queryParams.endDate = null
      // debugger
      if(!this.searchGroup){
        if (this.dateRangeTime) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTime[0]
          this.queryParams.endDate = this.dateRangeTime[1]
          this.queryParams.dateType = 1
        }
        pageAnalysis(this.queryParams).then(res => {
          this.list = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      }else {
        if (this.dateRangeTeam) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTeam[0]
          this.queryParams.endDate = this.dateRangeTeam[1]
          this.queryParams.dateType = 0

        }
        pageAnalysis(this.queryParams).then(res => {
          this.list = res.data.rows
          this.total = res.data.total
          this.loading = false
        })
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      // debugger
      if(this.queryParams.classesName === "" || this.queryParams.classesName === null){
        this.queryParams.dateType = 1;//天数据
      }else{
        this.queryParams.dateType = 0;//班组数据
      }

      // this.queryParams.pageNum = 1
      // this.setDateRangeTime()
      // this.getList()
     this.getData()


    },
    getData(){
      this.getConsumptionData()
      this.getCostConsumptionData();

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDownload() {
// debugger
      //查询时间统计表
      this.queryParams.beginDate = null
      this.queryParams.endDate = null
      // debugger
      if(!this.searchGroup){
        if (this.dateRangeTime) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTime[0]
          this.queryParams.endDate = this.dateRangeTime[1]
        }
        if(this.queryParams.tableType ===1)
        {
          exportSmeltingDay(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }else if(this.queryParams.tableType===2)
        {
          exportSmeltingMonth(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }else if(this.queryParams.tableType===3)
        {
          exportSmeltingYear(this.queryParams).then(res => {
            this.download(res.msg)
          })
        }


      }else {
        if (this.dateRangeTeam) { //数组不为空即为真
          this.queryParams.beginDate = this.dateRangeTeam[0]
          this.queryParams.endDate = this.dateRangeTeam[1]

        }
        exportSmeltingGroup(this.queryParams).then(res => {
          this.download(res.msg)
        })
      }

    },
    rebuild() {

        this.queryParams.dateType = 0
        this.rawDate = moment(new Date()).format('YYYY-MM-DD')

        this.getLastSche()//已经调用了getData



    },
    setTableType(){
      this.dateRangeTime=[,];
      this.handleQuery()
    },
    setYearRange(yearValue){
       debugger

      this.yearRange = yearValue;
       if(this.yearRange[0] !== '')
       {
         this.dateRangeTime[0] = `${yearValue[0]}-01-01 00:00:00`;
       }else{
         this.dateRangeTime[0]=null;
       }
      if(this.yearRange[1] !== '')
      {
        this.dateRangeTime[1] = `${yearValue[1]}-12-31 23:59:59`;
      }else{
        this.dateRangeTime[1]=null;
      }


        this.handleQuery();

    },
    setDateRangeTime() {
      // debugger
      if (this.queryParams.tableType === 2) {
        if(this.dateRangeTime)
        {
          this.dateRangeTime = [`${this.dateRangeTime[0]}-01 00:00:00`, `${this.dateRangeTime[1]}-01 00:00:00`]
        }

      }
       this.handleQuery();


    },
    setDateRange() {
      let year = this.queryParams.year
      let month = this.queryParams.month
      let day = this.queryParams.day
      if (this.searchType == 2) {
        this.dateRangeTeam = [`${year}-01-01`, `${year}-12-31`]
      }
      if (this.searchType == 3) {
        let startMoment = this.moment([year, month - 1, 1])
        this.dateRangeTeam = [startMoment.format('YYYY-MM-DD'), startMoment.endOf('month').format('YYYY-MM-DD')]
      }
      if (this.searchType == 4) {
        this.dateRangeTeam = [day, day]
      }
    },
    dateFormat(row){

      let date = row.rawDate
      return moment(date).format('YYYY-MM-DD')
      // if(this.searchGroup)
      // {
      //   return moment(date).format('YYYY-MM-DD')
      // }
      // if(row.tableType==1){
      //   return moment(date).format('YYYY-MM-DD')
      // }else if(row.tableType==2){
      //   return moment(date).format('YYYY-MM')
      // }else if(row.tableType==3){
      //   return moment(date).format('YYYY')
      // }else {
      //   return date
      // }

    },
    getConsumptionData(){

      this.queryParams.rawDate = this.rawDate
      console.log("this.queryParams.rawDate "+this.queryParams.rawDate+"   "+this.queryParams.classesName)
      this.consumptionList = [];
      this.pie1Data = [];
      this.pie1Legend = []
      this.barData = []
        this.barName=[]
      listConsumption(this.queryParams).then(res => {
        console.log("res "+res)
        if(res.data != null  && res.data.rows.length !==0){
          this.consumptionList = res.data.rows;
          // this.costConsumptionList = res.data
          this.consumptionList.forEach((item)=> {
            if(item.consumption > 0){
              this.pie1Data.push({value:item.consumption, name:item.matterName})
              this.pie1Legend.push(item.matterName)
              this.barName.push(item.matterName)
              this.barData.push(item.consumptionCost)
            }
          })
        }
        this.drawChart1()
        this.drawChart2()
      })

    },
    getCostConsumptionData(){
      this.queryHisParams.rawDate = this.rawDate
      console.log("queryHisParams "+this.queryHisParams)
      let _this= this

      getHisMatrialByDate(this.queryHisParams).then(res=>{
        console.log("res2 "+res)
        if(res.data != null){
          _this.dt = []
          _this.valueHisList.clear()
          // _this.valueHisList = []
          let result = res.data;
          for (var key in result){
              if(key === "dt")
              {
                let dtList = result[key]
                for(let i = 0; i<dtList.length;i++)
                {
                  var date =new Date(dtList.at(i));
                  _this.dt.push(`${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`) //result[key]
                }
              }else{
                _this.valueHisList.set(key,result[key]);
              }
          }

          this.drawChart3(_this.dt, _this.valueHisList)
        }
      })


      // listAnalysis(this.queryParams).then(res =>{
      //
      // })
    },
    initCanvas(){
      this.chart1Instance =  echarts.init(this.$refs.chart1);
      this.chart2Instance =  echarts.init(this.$refs.chart2);
      this.chart3Instance =  echarts.init(this.$refs.chart3);
      // this.drawChart1()
      // this.drawChart2()
      // this.drawChart3()
    },
    drawChart1(){
      const backgroundColor = '#00000000';
      var dataValue1=this.consumptionList;
      // var dataValue2=this.aggregateValue;
      const color = ['#e15e2b','#f7ec52', '#fedca7', '#dbbd7e','#ede9da','#98bcd5','#0487e2','#56cef6','#0463ca','#b0d6f5', '#0ab785', '#72fa93', '#a0e548', '#f5627b'];
      var option1 = {
        backgroundColor,
        color,
        title:{
          text: '各物料消耗信息',
          textStyle: {
            color: '#0463ca',
            fontSize: 20,
            fontWeight: 'bold'
          },
          //padding:100,
          top: '3%',
          // right:'10%',
          left: '60%',
        },
        legend:{
          //data，就是取得每个series里面的name属性。
          //orient: 'vertical',
          icon: 'circle', //图例形状
          padding: 0,
          // bottom: 'center',
          top:'15%',
          left:'40%',

          right: "1%",

          width:'60%',
          itemWidth: 15, //小圆点宽度
          itemHeight: 15, // 小圆点高度
          itemGap: 10, // 图例每项之间的间隔。[ default: 10 ]横向布局时为水平间隔，纵向布局时为纵向间隔。

          data:this.pie1Legend,
          //格式化图例文本
          formatter(name) {

            var value
            var unit
            var a
            for (var i = 0; i < dataValue1.length; i++) {
              if (dataValue1[i].matterName === name) {
                value =  dataValue1[i].consumption;
                unit = "吨"//dataValue1[i].unit;

                // num =  dataValue[i].value;
                // a = ((dataValue[i].value/ dataValue[i].total) * 100).toFixed(2)+ '%'
                a = value+unit;

                break;

              }
            }
            return [
              `{name|${name}}`,
              `      {a| ${a}}`,
            ].join("\n");
            // return [
            //   `{name|${name}}{a| ${a}}`,
            //   `      {num|${num}  个}`,
            // ].join("\n");
          },
          textStyle:{
            fontSize: 15,
            // padding: [28, 5, 0, 0],//上，右，下，左
            rich:{
              name:{
                fontSize: 15,
                color: "#000000",
                // fontWeight:'bolder',
                padding: [0, 0, 0, 0],//上，右，下，左
                align: 'left',
                // 文字块背景色，一定要加上，否则对齐不会生效
                backgroundColor: "transparent",
                width:80
              },
              // num: {
              //   fontSize: 14,
              //   color:'#c1c1c1',
              //   //align:'center',
              //   padding: [6, 0,6,0],
              // },
              a: {
                color: '#0463ca',
                fontSize: 16,
                fontWeight: 'bold',
                padding: [2, 0,0,-8],
                // width:"8%"
              },

            }
          }
        },

        series: [
          {

            type: 'pie',
            center: ['20%', '50%'], //圆心的位置
            top: '0%', //单单指的饼图距离上面的距离，top越大饼图越小
            left: '1%', //单单指的饼图距离左面的距离，会改变饼图的大小
            radius: ['10%', '90%'], //环形图的本质就在这里 [内半径!=0，外半径] 外半径越大，圆越大
            avoidLabelOverlap: false, //做同心圆用到
            clockwise:true, //顺时针排列
            startAngle: 270, //起始角度 影响不大
            roseType:"area", //area|radius

            label: {
              show: true, //false不显示饼图上的标签
              position: 'inner', //inside（在饼图上显示）,outside(默认就会出现引导线) center
              formatter:'{d}%',
              distance:0.5,//标识距离中心点的距离
              textStyle:{
                align:'center',
                // baseline:'middle',
                fontSize:8,
                color:'#000000',
                fontWeight:'bold'
              }
            },

            //只有设置了label:show=ture;position=outside 设置labelLine才会有效
            labelLine: {
              show: true, //显示引导线
              length: 30, //连接饼图第1段线条的长度 length length2 不写自适应
              length2: 10, //链接饼图第2段线条长度
              smooth: true, //是否光滑连接线
            },
            itemStyle: {
              //每个扇形的设置
              borderColor: 'rgba(0,0,0,.1)', //扇形边框颜色
              borderWidth: 0, //扇形边框大小 要先给borderColor颜色 设置borderWidth才会有效果

            },
            data:this.pie1Data.sort((a, b) => b.value - a.value), //数组从大到小排序

            // emphasis: {
            //   scale: true,
            //   scaleSize: 10,
            //
            //   //启用鼠标放上去放大效果，这个挺好的
            //   itemStyle: {
            //     shadowBlur: 10,
            //     shadowOffsetX: 0,
            //     shadowColor: 'rgba(0, 0, 0, 0.5)',
            //   },
            // },
          },
        ],
      };

      this.chart1Instance.setOption(option1)
    },
    drawChart2(){
      let optionDay = {
        title: {
          text: '各物料的吨矿成本分布',
          textStyle: {
            // color: '#0463ca',
            fontSize: 20,
            fontWeight: 'bold'
          },
          x:'35%',
          y: 'top',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          x: 'center',
          textStyle: {
            fontWeight: 900
          },
          // data: ['中心水泵房高压室', '精炼高压室', '炼钢本体高压室','3#水泵房高压室','总耗电量'],
          top: "0%",
          // bottom: "2%"
        },
        grid: {
          bottom: "10%",
          left: "6%",
          right: "4%",
          top: "10%",
          width: "92%",
          calculable: true,
        },
        xAxis: [
          {
            type: 'category',
            data: this.barName,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel:{
              interval:0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate:35   //调整数值改变倾斜的幅度（范围-90到90）
            }

          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '吨',
          },

          // {
          //   type: 'value',
          // }
        ],
        series: [
          {
            // name: '中心水泵房高压室',
            type: 'bar',
            barWidth : '30%',
            data: this.barData,
          },

        ]
      }
      this.chart2Instance.setOption(optionDay)
    },
    drawChart3(dtList,dataHisList){
      const color = ['#e15e2b','#f7ec52', '#fedca7', '#dbbd7e','#ede9da','#98bcd5','#0487e2','#56cef6','#0463ca','#b0d6f5', '#0ab785', '#72fa93', '#a0e548', '#f5627b'];
      let legendData = [];
      let seriesData = [];
      for (const [key, value] of dataHisList.entries()) {
          legendData.push(key)
          let seriesOption = {
            name: key,
            textStyle:{
              y:'10%',
            },

            type: 'line',
            // barWidth : '30%',
            data: value,
          };
          seriesData.push(seriesOption);
      }
      // for (let key in dataHisList){
      //   legendData.push(key)
      //   let seriesOption = {
      //     type: 'line',
      //     // barWidth : '30%',
      //     data: this.valueHisList[key],
      //   };
      //   seriesData.push(seriesOption);
      // }

      let optionDay = {
        title: {
          text: '各物料消耗变化趋势',
          textStyle: {
            // color: '#0463ca',
            fontSize: 20,
            fontWeight: 'bold'
          },
          x:'center',//'35%',
          y: 'bottom',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          x: 'center',
          textStyle: {
            fontWeight: 900
          },
          data:legendData,// ['中心水泵房高压室', '精炼高压室', '炼钢本体高压室','3#水泵房高压室','总耗电量'],
          top: "0%",
          // bottom: "2%"
        },
        grid: {
          bottom: "8%",
          left: "3%",
          right: "3%",
           // top: "10%",
          width: "92%",
          // height:"90%",
          containLabel: true, // 确保标签不被裁剪
          // calculable: true,
        },
        xAxis: [
          {
            type: 'category',
            data: dtList,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel:{
              interval:0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate:35   //调整数值改变倾斜的幅度（范围-90到90）
            }

          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '吨',
          },

          // {
          //   type: 'value',
          // }
        ],
        series:seriesData,
        //   [
        //   {
        //     // name: '中心水泵房高压室',
        //     type: 'line',
        //     // barWidth : '30%',
        //     data: this.barData,
        //   },
        //
        // ]
      }
      this.chart3Instance.setOption(optionDay)
    },
  }
}
</script>
<style lang="scss" scoped>
.tableStyle{
  ::v-deep th{
    text-align: center;
    //padding: 0px 0;
    //font-size: xx-small;
    //background-color:  #dcdcdc;
  }
  ::v-deep td{
    //padding: 0px 0;
    text-align: center;
    //font-size: xx-small
  }
}
</style>
